package entities;

import java.awt.*;
import java.net.Socket;
import java.util.Date;

/***
 * Author: Mr.Zhao, Time: 2018/5/25/11:09
 * Description: 玩家类
 */
public class Player {
    private String name = null;
    private Color color = null;
    private Player opponent = null;
    private Socket socket = null;
    //玩家在建立连接时的唯一标识，为了简单起见，用创建对象时的时间戳来表示
    private String id;

    public Player(Socket socket) {
        this.socket = socket;
        this.id = "" + new Date().getTime();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = color;
    }

    public Player getOpponent() {
        return opponent;
    }

    public void setOpponent(Player opponent) {
        this.opponent = opponent;
    }

    public Socket getSocket() {
        return socket;
    }

    public String getId() {
        return id;
    }

    /**
     * @return 处在空闲状态中的玩家信息
     */
    public String getFreeInfo() {
        return String.format("id：%s，地址：%s，端口号：%s",
                id, socket.getInetAddress(), socket.getPort());
    }

    /**
     * @return 处于对战状态中的玩家信息
     */
    public String getBusyInfo() {
        return String.format("id：%d，地址：%s，端口号：%s，棋子颜色：%s，对手信息：%s",
                id, socket.getInetAddress(), socket.getPort(), getColorName(), opponent.toString());
    }

    public String getColorName() {
        if (color == null) {
            return null;
        }
        return color == Color.RED ? "红色" : "黑色";
    }

    /**
     * @return 当前玩家有无对手
     */
    public boolean isBusy() {
        return this.opponent != null;
    }

    /**
     * @return 当前对象信息的json数据
     */
    @Override
    public String toString() {
        String opId = opponent == null ? null : "" + opponent.getId();
        return String.format("{\"id\":\"%s\",\"name\":\"%s\",\"color\":\"%s\"," +
                        "\"opponentId\":\"%s\",\"socket\":\"%s\",\"busy\":%b}",
                id, name, getColorName(), opId, socket.toString(), isBusy());
    }

    @Override
    public int hashCode() {
        return this.socket.hashCode() + this.id.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Player)) {
            return false;
        }
        Player temp = (Player) obj;
        return temp.socket.equals(this.socket);
    }


}
